function freshCanvas(step, VC) {
  VC.clearCanvas()

  for (let i = 0; i < step.length; i++) {
    step[i].draw(VC.ctx)
  }
}

function getSpeed(froms, tos, total) {

  let speeds = []

  for (let i = 0; i < tos.length; i++) {
    let from = findByKey(froms, tos[i].key)
    if (from) {
      let speedx = (tos[i].x - from.x) / total
      let speedy = (tos[i].y - from.y) / total
      speeds.push({ speedx, speedy, i })
    }

  }

  return speeds
}

export default function animate(froms, tos, VC, delay, callback) {

  if (tos.length === 0) {
    VC.clearCanvas()
    callback && callback()
    return
  }

  let moveCount = 0

  let interval = 5 + Math.ceil(5 * ((delay - 150) / 800))
  let total = 10 + Math.ceil(5 * ((delay - 150) / 800))

  let speeds = getSpeed(froms, tos, total)

  copyXY(froms, tos)

  VC.animateTimer = setInterval(() => {
    if (moveCount === total) {
      clearInterval(VC.animateTimer)
      callback && callback()
      return
    }

    let flag = false

    for (let i = 0; i < speeds.length; i++) {
      let item = speeds[i]
      let speedx = item.speedx
      let speedy = item.speedy
      if (speedx !== 0 || speedy !== 0) {
        flag = true
      }
      tos[item.i].x += speedx
      tos[item.i].y += speedy
    }

    freshCanvas(tos, VC)

    if (!flag) {
      // 说明是颜色改变，不需要移动
      moveCount = total
    } else {
      moveCount++
    }
  }, interval)
}

function copyXY(sources, dests) {
  for (let i = 0; i < dests.length; i++) {
    let source = findByKey(sources, dests[i].key)
    if (source) {
      dests[i].x = source.x
      dests[i].y = source.y
    }

  }
}

function findByKey(arr, key) {
  for (let i = 0; i < arr.length; i++) {
    if (arr[i].key === key) {
      return arr[i]
    }
  }
}